package cbh.tool.file;

import org.stringtemplate.v4.ST;
import org.stringtemplate.v4.STGroup;
import org.stringtemplate.v4.STGroupFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

/**
 * Created by hx-pc on 16-1-23.
 */
public class DataAccessObjectBuilder extends AbstractDocumentBuilder {

    private String entityPath;

    private String entityImport;

    private String className;

    private String nameSpace;

    private void reset() {
        String str = getC().getCanonicalName();
        entityPath = str.substring(0,str.lastIndexOf("."));
        entityImport = getC().getTypeName();
        className = getC().getSimpleName();
        nameSpace = getPropertits().nameSpace();
    }

    @Override
    public void create() {
        reset();
        STGroup stGroup = new STGroupFile("mybatis.dao.stg");
        ST stInterface = stGroup.getInstanceOf("interface");
        ST stImpl = stGroup.getInstanceOf("impl");
        stInterface.add("entityPath",entityPath);
        stInterface.add("entityImport",entityImport);
        stInterface.add("entityPath",entityPath);
        stInterface.add("className",className);
        stImpl.add("entityPath",entityPath);
        stImpl.add("entityImport",entityImport);
        stImpl.add("entityPath",entityPath);
        stImpl.add("nameSpace",nameSpace);
        stImpl.add("className",className);
        String interfaceTxt = stInterface.render();
        String implTxt = stImpl.render();
        File interfaceFile = new File(getBasePath()+"/dao/"+className+"Dao.java");
        FileOutputStream interfaceFos = null;
        OutputStreamWriter interfaceOsw = null;
        try {
            interfaceFile.createNewFile();
            interfaceFos = new FileOutputStream(interfaceFile);
            interfaceOsw = new OutputStreamWriter(interfaceFos);
            interfaceOsw.write(interfaceTxt);
            interfaceFos.flush();
            interfaceOsw.flush();
            interfaceFos.close();
            interfaceOsw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        File implFile = new File(getBasePath()+"/dao/"+className+"DaoImpl.java");
        FileOutputStream implFos = null;
        OutputStreamWriter implOsw = null;
        try {
            implFile.createNewFile();
            implFos = new FileOutputStream(implFile);
            implOsw = new OutputStreamWriter(implFos);
            implOsw.write(implTxt);
            implFos.flush();
            implOsw.flush();
            implFos.close();
            implOsw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
